<%@ taglib uri="/WEB-INF/iscTaglib.xml" prefix="isomorphic" %>

<%@ page import="com.isomorphic.base.Config" %>
    
<html>
<head>
<title>Standalone balsamiq mockup tool.</title>

</head>
<body>
<%
String skin = request.getParameter("skin");
if (skin == null || "".equals(skin)) skin = "Enterprise";
%>

<isomorphic:loadISC skin="<%=skin%>" modulesDir="system/development/" includeModules="Drawing,Charts,Analytics,FileLoader,FileBrowser,DocViewer,VisualBuilder" />
<script>
    <isomorphic:loadSystemSchema/>
    // what file to convert
    var mockupParam = isc.params.mockup;
    // output file to determine js or xml and file name
    var outputFileParam = isc.params.outputFile;
    var dropMarkupParam = isc.params.dropMarkup;
    var trimSpaceParam = isc.params.trimSpace;
    var fillSpaceParam = isc.params.fillSpace;
    var autoRefreshParam = isc.params.autoRefresh;
    var fieldNamingConventionParam = isc.params.fieldNamingConvention;
    var mockupUploadedParam = isc.params.mockupUploaded;

    var createBMMLImportDialog = function (dialogProperties) {
        dialogProperties = dialogProperties || {};

        RPCManager.actionURL = Page.getAppDir() + "bmmlImporterOperations.jsp";

        dialogProperties.submit = function (fileName, outputFileName, skin, dropMarkup, trimSpace, 
                fillSpace, fieldNamingConvention, autoRefresh, fileUploaded)
        {
            var url = isc.Page.getAppDir() + "bmmlImporter.jsp?mockup=" + fileName;
            if (outputFileName) {
                url += "&outputFile=" + outputFileName;
            }
            if (skin) {
                url += "&skin=" + skin;
            }
            if (fieldNamingConvention) {
                url += "&fieldNamingConvention=" + fieldNamingConvention;
            }
            if (!dropMarkup) {
                url += "&dropMarkup=no";
            }
            if (!trimSpace) {
                url += "&trimSpace=no";
            }
            if (!fillSpace) {
                url += "&fillSpace=no";
            }
            if (autoRefresh != null) {
                url += "&autoRefresh=" + autoRefresh;
            }
            if (fileUploaded) {
                url += "&mockupUploaded=yes";
            }
            window.location = url;
        };

        return isc.BMMLImportDialog.create(dialogProperties);
    };

    if (mockupParam && mockupParam.length > 0) {
        var mockupUrl = mockupParam;
        if (mockupUrl.startsWith("http://") || mockupUrl.startsWith("https://")) {
            mockupParam = null;
        } else {
            mockupUrl = null;
        }
        var bmmlImporter = isc.BMMLImporter.create({
            dropMarkup: dropMarkupParam != "no",
            trimSpace:  trimSpaceParam != "no",
            fillSpace:  fillSpaceParam != "no",
            mockupPath: mockupParam,
            fieldNamingConvention: fieldNamingConventionParam
        });
        var toolTitle = isc.Label.create({
            contents: "Balsamiq Importer",
            autoDraw: false
        });
        var autoRefreshDefaultValue = true;
        if (autoRefreshParam == "false") {
            autoRefreshDefaultValue = false;
        }
        var refreshCheckbox = isc.DynamicForm.create({
            ID: "refreshCheckbox",
            autoDraw: false,
            fields: [
                {name: "refresh", type: "checkbox", title: "Refresh automatically", defaultValue: autoRefreshDefaultValue,
                    changed : function (form, item, value) {
                        if (value && form.changeAction) {
                            form.changeAction();
                        }
                    }
                }
            ]
        });
        var downloadButton = isc.ToolStripButton.create({
            ID: "downloadButton",    
            title: "Download Source",
            icon: "[SKIN]actions/download.png",
            autoDraw: false,
            click : function () {
                isc.DMI.callBuiltin({
                    methodName: "downloadClientContent",
                    arguments: [ tools.xml, tools.xmlFileName, "text/xml" ],
                    requestParams: {
                        showPrompt:false,
                        useXmlHttpRequest: false,
                        timeout: 0
                    }
                 });
            }
            
        });
        var showButton = isc.ToolStripButton.create({
            ID: "showButton",    
            title: "Show Source",
            icon: "[SKIN]actions/view.png",
            autoDraw: false,
            _showingSource: false,
            click : function () {
                var taForm = isc.DynamicForm.create({
                    width: "100%",
                    height: "100%",
                    numCols: 1,
                    fields: [ {
                        name: "content",
                        type:"textArea", 
                        height: "100%", 
                        width: "*",
                        showTitle: false,
                        value: tools.xml} ]
                });
                var _this = this;
                this._showingSource = true;
                var wnd = isc.Window.create({
                    title: "Content",
                    height: "85%",
                    width: "85%",
                    autoCenter: true,
                    items: [taForm],
                    closeClick : function () {
                        _this._showingSource = false;
                        return this.Super("closeClick", arguments);
                    }
                });
                wnd.show();
                taForm.getItem("content").delayCall("selectValue", [], 100);
            }
        });
        var settingsButton = isc.ToolStripButton.create({
            ID: "settingsButton",
            title: "Settings..",
            icon: "[SKIN]/actions/configure.png",
            autoDraw: false,
            click : function () {
                var dialog = createBMMLImportDialog({
                    fileUrl: mockupUrl,
                    fileName: mockupParam,
                    outputFileName: outputFileParam,
                    skin: "<%=skin%>",
                    dropMarkup: dropMarkupParam != "no",
                    trimSpace: trimSpaceParam != "no",
                    fillSpace: fillSpaceParam != "no",
                    fieldNamingConvention: fieldNamingConventionParam,
                    autoRefresh: autoRefreshParam,
                    _fileUploaded: mockupUploadedParam == "yes"
                });
            }
        });
        var tools = isc.ToolStrip.create({
            width: "100%", height:24,
            layoutLeftMargin: 10,
            members: [toolTitle, settingsButton, downloadButton, showButton, refreshCheckbox],
            autoDraw: false
        });
        var canvas = isc.Canvas.create({
            overflow: "auto",
            autoDraw: false
        });
        isc.VLayout.create({
            width: "100%",
            height: "100%",
            members: [tools, canvas]
        });
        
        isc.Label.create({
            ID: "errLabel",
            width: 400,
            height: 20,
            top: 25,
            padding: 10,
            opacity: 0,
            contents: "<font color='red'>Can't auto-refresh mockup</font>" 
        });
        
        if (mockupUrl) {
            isc.RPCManager.sendProxied({
                actionURL: mockupUrl,
                callback: function (resp) {
                    var lastChangeDate = resp.httpHeaders["Last-Modified"];
                    if (mockupUrl.endsWith("/")) {
                        mockupUrl = mockupUrl.substring(0, url.length - 1);
                    }
                    var fileName = mockupUrl.substring(mockupUrl.lastIndexOf("/") + 1);
                    var contents = resp.data;
                    
                    var checkForChanges = function () {
                        if (refreshCheckbox.getValue("refresh") && !showButton._showingSource) {
                            isc.RPCManager.sendProxied({
                                actionURL: mockupUrl,
                                callback: function (resp) {
                                    if (resp.status == 0) {
                                        var dataLastChangeDate = resp.httpHeaders["Last-Modified"];
                                        var changed = false;
                                        if (lastChangeDate && dataLastChangeDate) {
                                            changed = lastChangeDate != dataLastChangeDate;
                                        } else {
                                            changed = contents != resp.data;
                                        }
                                        if (changed) {
                                            var href = window.location.href;
                                            if (href.contains("autoRefresh=false")) {
                                                href = href.replace("autoRefresh=false", "autoRefresh=true");
                                                window.location.replace(href);
                                            } else {
                                                window.location.reload();
                                            }
                                        }
                                    } else {
                                        errLabel.bringToFront();
                                        errLabel.animateFade(100);
                                        isc.Timer.setTimeout(function () {
                                            errLabel.animateFade(0);
                                        }, 5000);
                                    }
                                }
                            });
                        }
                    };
                    var checkForChangesScheduler = function () {
                        checkForChanges();
                        isc.Timer.setTimeout(checkForChangesScheduler, 10000);
                    }
                    isc.Timer.setTimeout(checkForChangesScheduler, 10000);
                    refreshCheckbox.changeAction = checkForChanges;

                    // convert bmml to smartclient
                    bmmlImporter.bmmlToXml(contents, function (xmlContent, layout) {
                        if (xmlContent == null) {
                            window.location = "bmmlImporter.jsp";
                            return;
                        }
                        tools.xml = xmlContent;
                        var onScriptEvaluated = function () {
                            for (var i = 0; i < layout.length; i++) {
                                var widget = layout[i];
                                if (widget._constructor != "ValuesManager" &&
                                    widget._constructor != "MockDataSource" &&
                                    window[widget.ID].parentElement == null) {
                                    canvas.addChild(window[widget.ID]);
                                }
                            }
                        }
                        
                        var ind = fileName.lastIndexOf(".");
                        var mockupFilePrefix = null;
                        if (ind > 0) {
                            mockupFilePrefix = fileName.substring(0, ind);
                        }
                        tools.xmlFileName = mockupFilePrefix + ".xml";
                        
                        if (outputFileParam) {
                            if (outputFileParam.substr(outputFileParam.length - 4) == ".xml") {
                                var path = outputFileParam;
                                if (!path.startsWith("/")) path = "tools/" + path;
                                isc.DMI.callBuiltin({
                                    methodName: "saveFile",
                                    arguments: [path, xmlContent]
                                });
                                tools.xmlFileName = outputFileParam;
                            } else {
                                ind = outputFileParam.lastIndexOf(".");
                                if (ind > 0) {
                                    tools.xmlFileName = outputFileParam.substring(0, ind);
                                } else {
                                    tools.xmlFileName = outputFileParam;
                                }
                                tools.xmlFileName += ".xml";
                            }
                            isc.DMI.callBuiltin({
                                methodName: "xmlToJS",
                                arguments: xmlContent,
                                callback : function (rpcResponse) {
                                    if (!outputFileParam ||
                                        outputFileParam.substr(outputFileParam.length - 3) == ".js") {
                                        var path = outputFileParam;
                                        if (!path.startsWith("/")) path = "tools/" + path;
                                        isc.DMI.callBuiltin({
                                            methodName: "saveFile",
                                            arguments: [
                                                path,
                                                rpcResponse.data
                                            ]
                                        });
                                    }
                                    isc.Class.evaluate(rpcResponse.data);
                                    onScriptEvaluated();
                                }
                            });
                        } else {
                            isc.DMI.callBuiltin({
                                methodName: "saveFile",
                                arguments: ["tools/" + mockupFilePrefix + ".xml", xmlContent]
                            });
                            isc.DMI.callBuiltin({
                                methodName: "xmlToJS",
                                arguments: xmlContent,
                                callback : function (rpcResponse) {
                                    isc.DMI.callBuiltin({
                                        methodName: "saveFile",
                                        arguments: [
                                            "tools/" + mockupFilePrefix + ".js",
                                            rpcResponse.data
                                        ]
                                    });
                                   isc.Class.evaluate(rpcResponse.data);
                                   onScriptEvaluated();
                                }
                            });
                        } 
                    });
                }
            });
        } else {
            // Load from file
            var fileSystemDs = isc.DataSource.getDataSource("Filesystem");
            // load bmml file
            fileSystemDs.fetchData({ path: mockupParam, webrootOnly: false },
            function (rpcResponse, data) {
                var contents = data[0].contents;
                var path = data[0].path;
                var ds = isc.DataSource.get("SCUploadSaveFile");
                
                var lastChangeDate = null;
                ds.fetchData({path: path}, function(dsResponse, data){
                    lastChangeDate = data.lastChangeDate;
                });
                
                var checkForChanges = function () {
                    if (refreshCheckbox.getValue("refresh") && !showButton._showingSource) {
                        ds.fetchData({path: path}, function(dsResponse, data) {
                            if (dsResponse.status == 0) {
                                if (lastChangeDate != data.lastChangeDate) {
                                    window.location.reload()
                                }
                            } else {
                                errLabel.bringToFront();
                                errLabel.animateFade(100);
                                isc.Timer.setTimeout(function () {
                                    errLabel.animateFade(0);
                                }, 5000);
                            }
                        }, {willHandleError: true});
                    }
                };
                var checkForChangesScheduler = function () {
                    checkForChanges();
                    isc.Timer.setTimeout(checkForChangesScheduler, 10000);
                }
                isc.Timer.setTimeout(checkForChangesScheduler, 10000);
                refreshCheckbox.changeAction = checkForChanges;
                        
                // convert bmml to smartclient
                bmmlImporter.bmmlToXml(contents, function (xmlContent, layout) {
                    if (xmlContent == null) {
                        window.location = "bmmlImporter.jsp";
                        return;
                    }
                    tools.xml = xmlContent;
                    var onScriptEvaluated = function () {
                        for (var i = 0; i < layout.length; i++) {
                            var widget = layout[i];
                            if (widget._constructor != "ValuesManager" &&
                                widget._constructor != "MockDataSource" &&
                                window[widget.ID].parentElement == null) {
                                canvas.addChild(window[widget.ID]);
                            }
                        }
                    }
                    var mockupFilePrefix = mockupParam;
                    var ind;
                    ind = mockupParam.lastIndexOf("/");
                    if (ind > 0) {
                        mockupFilePrefix = mockupFilePrefix.substring(ind);
                    }
                    ind = mockupFilePrefix.lastIndexOf("\\");
                    if (ind > 0) {
                        mockupFilePrefix = mockupFilePrefix.substring(ind);
                    }
                    ind = mockupFilePrefix.lastIndexOf(".");
                    if (ind > 0) {
                        mockupFilePrefix = mockupFilePrefix.substring(0, ind);
                    }
                    tools.xmlFileName = mockupFilePrefix + ".xml";
                    if (outputFileParam) {
                        if (outputFileParam.substr(outputFileParam.length - 4) == ".xml") {
                            var path = outputFileParam;
                            if (!path.startsWith("/")) path = "tools/" + path;
                            isc.DMI.callBuiltin({
                                methodName: "saveFile",
                                arguments: [path, xmlContent]
                            });
                            tools.xmlFileName = outputFileParam;
                        } else {
                            ind = outputFileParam.lastIndexOf(".");
                            if (ind > 0) {
                                tools.xmlFileName = outputFileParam.substring(0, ind);
                            } else {
                                tools.xmlFileName = outputFileParam;
                            }
                            tools.xmlFileName += ".xml";
                        }
                        isc.DMI.callBuiltin({
                            methodName: "xmlToJS",
                            arguments: xmlContent,
                            callback : function (rpcResponse) {
                                if (!outputFileParam ||
                                    outputFileParam.substr(outputFileParam.length - 3) == ".js") {
                                    var path = outputFileParam;
                                    if (!path.startsWith("/")) path = "tools/" + path;
                                    isc.DMI.callBuiltin({
                                        methodName: "saveFile",
                                        arguments: [
                                            path,
                                            rpcResponse.data
                                        ]
                                    });
                                }
                                isc.Class.evaluate(rpcResponse.data);
                                onScriptEvaluated();
                            }
                        });
                    } else {
                        var toolsMockupFilePrefix = "tools";
                        if (!mockupFilePrefix.startsWith("/")) {
                            toolsMockupFilePrefix += "/";
                        }
                        toolsMockupFilePrefix += mockupFilePrefix;
                        isc.DMI.callBuiltin({
                            methodName: "saveFile",
                            arguments: [toolsMockupFilePrefix + ".xml", xmlContent]
                        });
                        isc.DMI.callBuiltin({
                            methodName: "xmlToJS",
                            arguments: xmlContent,
                            callback : function (rpcResponse) {
                                isc.DMI.callBuiltin({
                                    methodName: "saveFile",
                                    arguments: [
                                        toolsMockupFilePrefix + ".js",
                                        rpcResponse.data
                                    ]
                                });
                               isc.Class.evaluate(rpcResponse.data);
                               onScriptEvaluated();
                            }
                        });
                    }
                });
            }, {operationId: "loadFile"});
        }
    } else {
        createBMMLImportDialog();
    }
</script>
</body>
</html>
